<?php

namespace App\Library\FormFields;

use App\Library\OSS;
use Kris\LaravelFormBuilder\Fields\FormField;
use Kris\LaravelFormBuilder\Form;

class ImageListType extends FormField
{
    private $uploadUrl;
    private $widgetId;

    public function __construct(string $name, string $type, Form $parent, array $options = [])
    {
        parent::__construct($name, $type, $parent, $options);
        $this->parent->setFormOption('files', true);

        if (isset($options['upload_url']) && !is_null($options['upload_url'])) {
            $this->uploadUrl = $options['upload_url'];
        } elseif (isset($options['type']) && !is_null($options['type'])) {
            $this->uploadUrl = route('admin.upload_image', ['type' => $options['type']]);
        }

        $this->widgetId = 'image_list_' . random_int(0, 999999);
    }

    /**
     * @inheritDoc
     */
    protected function getTemplate()
    {
        return 'vendor.laravel-form-builder.image_list';
    }

    /**
     * @inheritDoc
     */
    public function render(array $options = [], $showLabel = true, $showField = true, $showError = true)
    {
        return parent::render($options, $showLabel, $showField, $showError);
    }

    public function getRenderData()
    {
        $urls = [];
        if (!empty($this->getValue())) {
            foreach ($this->getValue() as $file) {
                $urls[$file] = OSS::instance()->getUrl($file);
            }
        }

        return [
            'uploadUrl' => $this->uploadUrl,
            'widgetId' => $this->widgetId,
            'urlMap' => $urls,
        ];
    }
}
